<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use think\Request;

class Rechargerule extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->defaultOrder = 'create_date DESC';
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $info['rule_json'] = json_decode($info['rule_json'], true);

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();
            $ruleJson = [];
            if(isset($data['recharge_money']) && $data['recharge_money']){
                foreach ($data['recharge_money'] as $key => $val) {
                    if(!trim($val)){
                        continue;
                    }
                    $ruleJson[] = [
                        'recharge_money' => $val * 100,
                        'gift_money' => $data['gift_money'][$key] * 100
                    ];
                }
            }
            $data['rule_json'] = json_encode($ruleJson);

            if ($data['id']) {
                // Update data
                if($data['status'] == 2){
                    // 该充值模板是否已被使用
                    $usedInfo = $this->isUsed($data['id']);
                    if($usedInfo['code'] != 1){
                        return $this->error($usedInfo['msg']);
                    }
                }

                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                $logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_update';
            } else {
                // Insert data
                $data['status'] = 1;
                $result = $model->save($data);
                $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                $afterAction = '_after_insert';
            }

            if($result !== false) {
                // Query执行后的操作
                $model->$afterAction($data);

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();

            // 该充值模板是否已被使用
            $usedInfo = $this->isUsed($data['id']);
            if($usedInfo['code'] != 1){
                return $this->error($usedInfo['msg']);
            }

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        // 该充值模板是否已被使用
        $usedInfo = $this->isUsed($id);
        if($usedInfo['code'] != 1){
            return $this->error($usedInfo['msg']);
        }

        $result = $model->where('id', $id)->delete();
        if ($result !== false) {
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            if($item['rule_json']){
                $rules = json_decode($item['rule_json'], true);
                $rulesStr = '';
                foreach($rules as $rule){
                    $rulesStr .= ',充' . $rule['recharge_money'] / 100 . '元送' . $rule['gift_money'] / 100 . '元';
                }
                $item['rule_json'] = substr($rulesStr, 1);
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }

        return $where;
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id){
        if(!$id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有使用该充值模板的会员等级
        $levelWhere = [
            'recharge_rule_id' => $id,
            //'status' => 1
        ];
        $memberlevel = \app\admin\model\Memberlevel::where($levelWhere)->find();
        if($memberlevel){
            return ['code' => 0, 'msg' => '有使用该充值模板的会员等级，请先删除会员等级'];
        }

        return ['code' => 1, 'msg' => ''];
    }

}